package com.hbq.codedemopersion.common.controller.test;

import com.hbq.codedemopersion.common.model.A;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class MergeGroup {
    public static void main(String[] args) {
        A a = A.builder().name("a").age(1).build();
        A b = A.builder().name("b").age(1).build();
        A c = A.builder().name("a").age(2).build();

        A d = A.builder().name("d").age(3).build();
        A e = A.builder().name("e").age(3).build();

        A f = A.builder().name("f").age(5).build();
        List<A> newList = new ArrayList<>();
        int groupNum = addGroup(List.of(a, b, c, d, e, f), newList);

        newList.stream().collect(Collectors.groupingBy(A::getGroup)).forEach((k, v) -> System.out.println(k + "|||" + v));
        System.out.println("一共" + groupNum + "组");
    }

    /**
     * 把原集合添加组别给新集合
     * @param list 原集合
     * @param newList 新集合
     * @return 组数
     */
    private static int addGroup(List<A> list, List<A> newList) {
        int groupNum = 0;
        for (A item : list) {
            for (A newItem : newList) {
                if (item.getName().equals(newItem.getName()) || item.getAge().equals(newItem.getAge())) {
                    item.setGroup(newItem.getGroup() == null ? ++groupNum : newItem.getGroup());
                    break;
                }
            }
            if (item.getGroup() == null) {
                item.setGroup(++groupNum);
            }
            newList.add(item);
        }
        return groupNum;
    }
}